package com.example.ymm.modules1.service.impl.hl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.dkn.DknProductMapping;
import com.example.ymm.modules1.entity.hl.dkn.DknPurchaseOrder;
import com.example.ymm.modules1.mapper.hl.DknPurchaseOrderMapper;
import com.example.ymm.modules1.query.hl.DknProductMappingQueryCriteria;
import com.example.ymm.modules1.query.hl.DknPurchaseOrderQueryCriteria;
import com.example.ymm.modules1.service.dkn.DknOrderService;
import com.example.ymm.modules1.service.dto.dkn.DknEditOrderDto;
import com.example.ymm.modules1.service.dto.heng.DknCreatePurchaseOrderGroupDto;
import com.example.ymm.modules1.service.dto.heng.DknProductMappingDto;
import com.example.ymm.modules1.service.dto.ms.MsOrderListQueryCriteria;
import com.example.ymm.modules1.service.hl.DknProductMappingService;
import com.example.ymm.modules1.service.hl.DknPurchaseOrderService;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
@DS("slave2")
public class DknPurchaseOrderServiceImpl extends BaseServiceImpl<DknPurchaseOrderMapper, DknPurchaseOrder>
        implements DknPurchaseOrderService {

    @Autowired
    DknOrderService dknOrderService;

    @Autowired
    DknProductMappingService dknProductMappingService;


    @Override
    public TableList<DknPurchaseOrder> list(DknPurchaseOrderQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DknPurchaseOrder> page = new Page<DknPurchaseOrder>(pageDto.getPage(), pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DknPurchaseOrder.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DknPurchaseOrder> tableList = new TableList(page);
        List<DknPurchaseOrder> list = tableList.getList();
//        for (DknPurchaseOrder order : list) {
//            if(UtilValidate.isNotEmpty(order.getOrderCode())){
//                JsonNode jsonNode = dknOrderService.getOrderDetail(order.getOrderCode());
//                if(jsonNode.has("header")){
//                    JsonNode orderHeader = jsonNode.get("header");
//                    order.setOrderStatus(orderHeader.get("status").asText());
//                }
//
//            }
//
//        }
        return tableList;
    }

    public List<DknPurchaseOrder> queryAll(DknPurchaseOrderQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DknPurchaseOrder.class, criteria);
        predicate.orderByDesc("create_time");
        List<DknPurchaseOrder> result = baseMapper.selectList(predicate);
        return result;
    }


    @Override
    public List<DknCreatePurchaseOrderGroupDto> purchaseOrderWaitList(DknPurchaseOrderQueryCriteria criteria) {
        return baseMapper.purchaseOrderWaitList(criteria);
    }

    /**
     * 查询 迪卡侬 采购下单状态
     */
    @Override
    public void queryDknOrders() {
        DknPurchaseOrderQueryCriteria criteria=new DknPurchaseOrderQueryCriteria();
//        criteria.setInquiryStatus("placed");
        List<String> statusList=new ArrayList<>();
        statusList.add("placed");
        statusList.add("created");
        criteria.setInquiryStatusIn(statusList);
        List<DknPurchaseOrder> lists = queryAll(criteria);
        for (DknPurchaseOrder order : lists) {
            JsonNode jsonNode = dknOrderService.inquiriesOrder(order.getInquiryCode());
            DknPurchaseOrder n_order = new DknPurchaseOrder();
            n_order.setInquiryCode(order.getInquiryCode());
            n_order.setInquiryStatus(jsonNode.get("inquiry_status").asText());
            n_order.setRemark(jsonNode.get("message").asText());
            if(jsonNode.has("orderHeader")){
                JsonNode orderHeader = jsonNode.get("orderHeader");
                n_order.setOrderStatus(orderHeader.get("order_status").asText());
                String orderCode = orderHeader.get("order_code").asText();
                dknOrderService.validationOrder(orderCode);
                n_order.setOrderCode(orderCode);
            }
            updateById(n_order);
        }
    }


    @Override
    public void orderStatusDknOrders() {
        DknPurchaseOrderQueryCriteria criteria=new DknPurchaseOrderQueryCriteria();
        criteria.setOrderCodeIsNotNull("1");
        List<DknPurchaseOrder> lists = queryAll(criteria);
        for (DknPurchaseOrder order : lists) {
            if(UtilValidate.isNotEmpty(order.getOrderCode())){
                JsonNode jsonNode = dknOrderService.getOrderDetail(order.getOrderCode());
                if(jsonNode.has("header")){
                    JsonNode orderHeader = jsonNode.get("header");
                    String new_status = orderHeader.get("status").asText();
                    if(!order.getOrderStatus().equals(new_status)){
                        DknPurchaseOrder n_order = new DknPurchaseOrder();
                        n_order.setInquiryCode(order.getInquiryCode());
                        n_order.setOrderStatus(new_status);
                        updateById(n_order);
                    }

                }

            }

        }
    }

    @Override
    public void orderCancel(DknPurchaseOrder order) {
        JsonNode jsonNode = dknOrderService.postCancelOrder(order.getOrderCode());
        System.out.println("---"+jsonNode);
        String error= jsonNode.get("error").asText();
        String error_description= jsonNode.get("error_description").asText();
        if(UtilValidate.isNotEmpty(error_description)){
            String e_s="取消异常："+error_description;
            DknPurchaseOrder u_order = new DknPurchaseOrder();
            u_order.setInquiryCode(order.getInquiryCode());
            u_order.setNote(e_s);
            updateById(u_order);
            throw new YmException(error_description);
        }
        removeById(order);

    }

    @Override
    public JsonNode orderDetail(DknPurchaseOrder order) {
        JsonNode jsonNode = dknOrderService.getOrderDetail(order.getOrderCode());
        if(jsonNode.has("header")){
            JsonNode orderHeader = jsonNode.get("header");
            String new_status = orderHeader.get("status").asText();
            if(!order.getOrderStatus().equals(new_status)){
                DknPurchaseOrder n_order = new DknPurchaseOrder();
                n_order.setInquiryCode(order.getInquiryCode());
                n_order.setOrderStatus(new_status);
                updateById(n_order);
            }

        }
        return jsonNode;
    }

    @Override
    public void orderEdit(DknEditOrderDto dto) {
        JsonNode jsonNode = dknOrderService.postEditItem(dto);
        System.out.println("---"+jsonNode);
    }

    @Override
    public JSONArray orderItemList(String inquiryCode) {
        JSONArray jsonArray=new JSONArray();
        DknPurchaseOrder purchaseOrder = getById(inquiryCode);
        if(UtilValidate.isNotEmpty(purchaseOrder.getParameter())){

            MsOrderListQueryCriteria criteria=new MsOrderListQueryCriteria();
            criteria.setOrderNo(purchaseOrder.getOrderNo());
            JsonNode orderDetail = dknOrderService.getLines(purchaseOrder.getOrderCode());
             jsonArray =JSONObject.parseArray(orderDetail.toString());
             List<String> itemCodes=new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String itemCode = jsonObject.containsKey("component_reference")?jsonObject.getString("component_reference"):jsonObject.getString("finished_good_item_code");
                itemCodes.add(itemCode);

            }
            DknProductMappingQueryCriteria c2=new DknProductMappingQueryCriteria();
            c2.setItemCodes(itemCodes);
            List<DknProductMapping> mappings = dknProductMappingService.queryAll(c2);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String itemCode = jsonObject.containsKey("component_reference")?jsonObject.getString("component_reference"):jsonObject.getString("finished_good_item_code");
                for(DknProductMapping m : mappings){
                    if(m.getItemCode().equals(itemCode)){
                        jsonObject.put("mtid",m.getMtid());
                        jsonObject.put("item_name",m.getItemName());
                    }
                }
            }

        }
        return jsonArray;
    }
}
